import CryptoJS from "crypto-js";
import RecorderManager from "./js/RecorderManager";
import dayjs from "dayjs";
// 系统配置
const config = {
  // 请求地址
  hostUrl: "wss://rtasr.xfyun.cn/v1/ws",
  // appid: "ee62ae20",
  // apiKey: "a90b5ce28ebf3375a58dd00602a2a3e3",
  appid: "e364cd18",
  apiKey: "0fcd2d2c1baad02dbe978cb491402ba4",
};
let recordStartTime;
let iatWS;
let recorder;
let listenFunc;
let resultText = "";
let resultTextTemp = "";
const recordStatusEnum = {
  init: 0,
  recording: 1,
  pause: 2,
  end: 3,
};

export const start = () => {
  recorder = new RecorderManager("");
  recorder.onStart = () => {
    //   changeBtnStatus("OPEN");
  };
  recorder.onFrameRecorded = (val) => {
    let { isLastFrame, frameBuffer } = val;
    if (iatWS.readyState === iatWS.OPEN) {
      iatWS.send(new Int8Array(frameBuffer));
      if (isLastFrame) {
        iatWS.send('{"end": true}');
        //   changeBtnStatus("CLOSING");
      }
    }
  };
  recorder.onStop = () => {
    console.log("stop~~~~~~");
    if (iatWS) {
      iatWS.close(1000, "Normal closure"); // 推荐使用标准关闭码
      iatWS = null; // 清除引用
    }
    //   clearInterval(countdownInterval);
  };
  console.log("RecorderManager", recorder);
};

//   签名
const getSigna = (ts) => {
  let md5 = CryptoJS.MD5(config.appid + ts).toString();
  let sha1 = CryptoJS.HmacSHA1(md5, config.apiKey);
  let base64 = CryptoJS.enc.Base64.stringify(sha1);
  return encodeURIComponent(base64);
};

const changeBtnStatus = (status) => {
  btnStatus = status;
  if (status === "CONNECTING") {
    // setBtnTxt("建立连接中");
    // setResultVal("");
    resultText = "";
    resultTextTemp = "";
  } else if (status === "OPEN") {
    // setBtnTxt("录音中...");
  } else if (status === "CLOSING") {
    // setBtnTxt("关闭连接中");
  } else if (status === "CLOSED") {
    // setBtnTxt("开始录音");
  }
};

let allResult = [];
const recordCurrentTime = () => {
  const now = new Date().getTime(); //开始毫秒
  return dayjs(now - recordStartTime - 1000 * 60 * 60 * 8).format("HH:mm:ss");
};
const setAllResult = (isSwitch, t) => {
  // console.log(887, t);
  if (isSwitch || allResult.length === 0) {
    const newSection = {
      user: "客户",
      time: recordCurrentTime(),
      content: t,
    };
    allResult = [...allResult, newSection];
    return allResult;
  } else {
    const lastIndex = allResult.length - 1;
    let lastSection = allResult[lastIndex];
    lastSection.content += t;
    allResult.splice(lastIndex, 1, lastSection);
    return allResult;
  }
};

const renderResult = (resultData) => {
  let jsonData = JSON.parse(resultData);
  // console.log("收到消息：", jsonData);

  if (jsonData.action == "started") {
    // 握手成功
    console.log("握手成功");
  } else if (jsonData.action == "result") {
    const data = JSON.parse(jsonData.data);
    // 转写结果
    resultTextTemp = "";
    const endTag = data.cn.st.type == 0; // 一句话正式结束标记
    data.cn.st.rt.forEach((j) => {
      j.ws.forEach((k) => {
        k.cw.forEach((l) => {
          // console.log("***,", l.w);
          // if (l.rl > 0) {
          //   if (
          //     l.w.startsWith("。") ||
          //     l.w.startsWith("！") ||
          //     l.w.startsWith("？")
          //   ) {
          //     let mark = i.w.slice(0, 1);
          //     let w = l.w.slice(1);

          //   }else{

          //   }
          //   console.log("换人了>>>>", resultTextTemp);
          //   listenFunc && listenFunc(setAllResult(true, l.w));
          // } else {
          //   // resultTextTemp += l.w;
          //   listenFunc && listenFunc(setAllResult(false, l.w));

          // }
          // if (l.rl > 0) {
          //   console.log("换人了>>>>1", l.w);
          //   console.log("换人了>>>>2", resultTextTemp);
          //   if (endTag) {
          //     // resultText += resultTextTemp;
          //     setAllResult(true, resultTextTemp);
          //     resultTextTemp = "";
          //   } else {
          //   }
          // }
          // resultTextTemp += l.w;
          if (l.rl > 0 && endTag) {
            // 换人标志，需要把以前的resultTextTemp追加到末尾
            setAllResult(false, resultTextTemp);
            // 开启新的段
            setAllResult(true, "");
            resultTextTemp = "";
          }
          resultTextTemp += l.w;
        });
      });
    });

    if (endTag) {
      // listenFunc && listenFunc(setAllResult(false, resultTextTemp));
      // 【最终】一句话识别结果：
      resultText += resultTextTemp;
      // console.log("#####1", resultTextTemp);
      // console.log("#####2", resultText);
      // setAllResult(false, resultTextTemp);

      // setResultVal(resultText);

      // return console.log("#####9", resultText + resultTextTemp);
      // console.dir(data)
      console.log("111", resultText);
      // 把当前数据加入到allResult
      setAllResult(false, resultTextTemp);
      // listenFunc && listenFunc(allResult, resultTextTemp);
    }
    listenFunc && listenFunc(allResult, resultTextTemp);

    // listenFunc && listenFunc(setAllResult(false, resultTextTemp));
    // console.log("#####3", resultText + resultTextTemp);

    // console.log("###01", resultTextTemp);
    // listenFunc && listenFunc(isNew, resultTextTemp);

    // setResultVal(resultText + resultTextTemp);

    // listenFunc && listenFunc(resultText + resultTextTemp);
  } else if (jsonData.action == "error") {
    // 连接发生错误
    console.log("出错了:", jsonData);
  }
};

const connectWebSocket = () => {
  let ts = parseInt(new Date().getTime() / 1000);
  let websocketUrl =
    config.hostUrl +
    "?appid=" +
    config.appid +
    "&ts=" +
    ts +
    "&roleType=2" +
    "&signa=" +
    getSigna(ts);
  if ("WebSocket" in window) {
    iatWS = new WebSocket(websocketUrl);
  } else if ("MozWebSocket" in window) {
    iatWS = new MozWebSocket(websocketUrl);
  } else {
    alert("浏览器不支持WebSocket");
    return;
  }
  // changeBtnStatus("CONNECTING");
  iatWS.onopen = (e) => {
    // 开始录音
    recorder.start({
      sampleRate: 16000,
      frameSize: 1280,
    });
  };
  iatWS.onmessage = (e) => {
    renderResult(e.data);
  };
  iatWS.onerror = (e) => {
    console.error(e);
    recorder.stop();
    // changeBtnStatus("CLOSED");
  };
  iatWS.onclose = (e) => {
    recorder.stop();
    // changeBtnStatus("CLOSED");
  };
};

export const recordStart = (func) => {
  start();
  listenFunc = func;
  connectWebSocket();
  recordStartTime = new Date().getTime(); //开始毫秒
};

export const pause = () => {
  recorder.stop();
};

export const goOn = () => {
  connectWebSocket();
};

export const stop = () => {
  recorder.stop();
  setTimeout(() => {
    console.log("清除~~");
    listenFunc = null;
    resultText = null;
    resultTextTemp = null;
    recordStartTime = null; //开始毫秒
    allResult = [];
  }, 5000);
};
